package com.atguigu.day10;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Json;
import org.apache.flink.table.descriptors.Kafka;
import org.apache.flink.table.descriptors.Schema;
import org.apache.kafka.clients.producer.ProducerConfig;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.e;

public class Flink08_SQL_Demo {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<WaterSensor> waterSensorStream =
                env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                        new WaterSensor("sensor_1", 2000L, 20),
                        new WaterSensor("sensor_2", 3000L, 30),
                        new WaterSensor("sensor_1", 4000L, 40),
                        new WaterSensor("sensor_1", 5000L, 50),
                        new WaterSensor("sensor_2", 6000L, 60));

        //2.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //流转表
//        Table sourceTable = tableEnv.fromDataStream(waterSensorStream);

//        Table table = tableEnv.sqlQuery("select id,sum(vc) as vcSum from " + sourceTable + " group by id");

        //打印方式一：将表转为流并打印
//        tableEnv.toAppendStream(table, WaterSensor.class).print();

//        env.execute();

        //打印方式二：将Table转为TableResult并打印
//        TableResult tableResult = table.execute();
//        tableResult.print();

        //打印方式三：直接调用executeSql方法执行sql会返回一个TableResult对象，可以用对其直接打印
        //TODO 查询未注册的表(没有表名)
//        TableResult tableResult = tableEnv.executeSql("select id,sum(vc) as vcSum from " + sourceTable + " group by id");

//        tableResult.print();

        //TODO 查询已注册的表
        //先注册（实质就是注册一个表名）
        //对Table对象注册
//        tableEnv.createTemporaryView("sensor", sourceTable);

        //直接对流进行注册
        tableEnv.createTemporaryView("sensor", waterSensorStream);

        tableEnv.executeSql("select id,sum(vc) from sensor group by id").print();
    }
}
